package com.scs.application.core.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 */
public class WebUtils {

    public static final String AUTHORIZATION_HEADER = "Authorization";

    /**
     * 在shiro的filter中不能调用，否则会报 NPE
     *
     * @return
     */
    public static HttpServletRequest getHttpRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static String getRequestIp() {
        return IPUtils.getIpAddr(WebUtils.getHttpRequest());
    }

    public static String getAccessToken(HttpServletRequest request) {
        if(request == null){
            request = getHttpRequest();
        }
        //从header中获取token
        String token = request.getHeader(AUTHORIZATION_HEADER);

        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(AUTHORIZATION_HEADER);
        }

        // 如果参数中不存在token，从Cookie中获取token
        if (StringUtils.isBlank(token)) {

            Cookie[] cookies = request.getCookies();
            if (cookies == null || cookies.length == 0) {
                return null;
            }
            for (Cookie cookie : cookies) {
                if (AUTHORIZATION_HEADER.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }

        }

        return token;
    }

    /**
     * 获取访问令牌。获取当前上下文的request（有可能获取不到），这时使用 {@link }
     * @return
     */
    public static String getAccessToken() {
       return getAccessToken(getHttpRequest());
    }

    /**
     * 获取当前仓库
     */
    public static String getCurrentWarehouse(){
        return getCurrentWarehouse(getHttpRequest());
    }
    public static String getCurrentWarehouse(HttpServletRequest request){
        if(request != null){
            request = getHttpRequest();
        }
        String warehouseId = request.getHeader("warehouseId");
        return warehouseId;
    }

}
